package com.yuanda.erp9.syn.service.erp9.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.innovation.ic.b1b.framework.util.StringUtils;
import com.yuanda.erp9.syn.contant.ExeConstant;
import com.yuanda.erp9.syn.contant.RateCalculateConstants;
import com.yuanda.erp9.syn.entity.CmsBrandsTempEntity;
import com.yuanda.erp9.syn.entity.CmsGoodsEntity;
import com.yuanda.erp9.syn.entity.CmsGoodsInformationEntity;
import com.yuanda.erp9.syn.entity.CmsPricesEntity;
import com.yuanda.erp9.syn.enums.CachePrefixEnum;
import com.yuanda.erp9.syn.enums.DeliveryAreaEnum;
import com.yuanda.erp9.syn.enums.SourceEnum;
import com.yuanda.erp9.syn.enums.SubjectSupplierEnum;
import com.yuanda.erp9.syn.exception.TargetServerException;
import com.yuanda.erp9.syn.execule.thread.Master;
import com.yuanda.erp9.syn.helper.RetryOperateLogHelper;
import com.yuanda.erp9.syn.helper.SelfSupportHelper;
import com.yuanda.erp9.syn.pojo.CmsGoodsPojo;
import com.yuanda.erp9.syn.service.erp9.CmsTopicUpdateSumLogService;
import com.yuanda.erp9.syn.service.erp9.SelfSupportService;
import com.yuanda.erp9.syn.util.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

/**
 * @ClassName SelfSupportServiceImpl
 * @Description
 * @Date 2023/1/6
 * @Author myq
 */
@Slf4j
@Service
public class SelfSupportServiceImpl implements SelfSupportService {

    @Resource
    private SelfSupportHelper selfSupportHelper;

    @Resource
    private RetryOperateLogHelper retryOperateLogHelper;

    @Resource
    private CmsTopicUpdateSumLogService cmsTopicUpdateSumLogService;

    private final String SUPPLIER = "b1b.com";
    private final String US_CODE = "US000000053";

    /**
     * @Description: 解析自营数据
     * @Params:
     * @Return:
     * @Author: Mr.myq
     * @Date: 2023/1/615:03
     */
    @Override
    public void parse(Long pk) {
        AtomicInteger sum = new AtomicInteger(0);
        CacheUtil.Cache brandCache = CacheUtil.init(CachePrefixEnum.BRAND.getKey());
        CacheUtil.Cache supplierCache = CacheUtil.init(CachePrefixEnum.SUPPLIERS.getKey());
        Integer supplierId = supplierCache.get(SUPPLIER);
        Master<CmsGoodsPojo> objectMaster = null;
        Set<String> stringSet = new HashSet<>();
        // 读取sunload,xls文件
        Map<String, Map<String, String>> sunloadMap = selfSupportHelper.readExcelGetList(supplierId);
        List<String> arrCollect = null;
        try {
            InputStream inputStream = new ClassPathResource(ExeConstant.SUNLOCAL_CSV_PATH).getInputStream();
            List<String[]> arr = CsvReadUtils.parseCSVByInputStream(inputStream);
            Assert.notEmpty(arr, "读取自营CSV文件异常");
            arrCollect = arr.stream().map(e -> String.valueOf(e[0])).collect(Collectors.toList());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        try {
            int page = 1;
            JSONObject rowLineJsonStr = null;
            for (int x = 0; x < 2; x++) {
                while (true) {
                    // 结果集
                    JSONObject httpGetData = selfSupportHelper.sendHttpAndGetData(x, page);
                    if (objectMaster == null) {
                        objectMaster = new Master<>(supplierId, null, SourceEnum.DATA_PACKAGE.getCode());
                    }
                    Integer pageinfo = JSON.parseObject(httpGetData.getString("pageInfo")).getInteger("pages");
                    log.debug("正在解析TypeId为：" + x + "数据， " + "当前page ： " + pageinfo);
                    if (page <= pageinfo) {
                        try {
                            sum.incrementAndGet();
                            page++;
                            JSONArray resDataList = httpGetData.getJSONArray("list");
                            for (int y = 0; y < resDataList.size(); y++) {
                                CmsGoodsPojo pojo = new CmsGoodsPojo();
                                // 行数据
                                JSONObject row = JSONObject.parseObject(resDataList.get(y).toString());
                                rowLineJsonStr = row;
                                int moq = 1;
                                String warehouse = row.getString("仓库");
                                //商品类
                                CmsGoodsEntity cmsGoodsEntity = new CmsGoodsEntity();
                                cmsGoodsEntity.setAdminid(0);
                                cmsGoodsEntity.setTenantsid(0);
                                cmsGoodsEntity.setClassifyid(0);
                                cmsGoodsEntity.setImg("");
                                cmsGoodsEntity.setType(0);
                                cmsGoodsEntity.setStatus(1);
                                cmsGoodsEntity.setStatusMsg("");
                                cmsGoodsEntity.setDataType(1);
                                cmsGoodsEntity.setModel(row.getString("PARTNO"));
                                CmsBrandsTempEntity cmsBrandsTempEntity = new CmsBrandsTempEntity();
                                cmsBrandsTempEntity.setTag(0);
                                String brand = row.getString("MFC");
                                if (brand.equals("uniohm")) {
                                    continue;
                                }
                                if (Arrays.asList("TAIYO", "TAIYO YUDEN").contains(brand)) {
                                    brand = "Taiyo Yuden";
                                } else {
                                    brand = brand.length() > 1 ? brand : "";
                                }
                                cmsBrandsTempEntity.setName(StringUtils.isNotEmpty(brand) ? brand : "unknown_brand");
                                Integer brandId = brandCache.insertAndGet(cmsBrandsTempEntity);
                                cmsGoodsEntity.setBrand(brandId);
                                cmsGoodsEntity.setBrandName(brand);
                                cmsGoodsEntity.setSupplier(supplierId);
                                cmsGoodsEntity.setSplName(SUPPLIER);
                                String detailId = row.getString("明细ID");
                                if (Arrays.asList("2378677", "3094216").contains(detailId)) {
                                    continue;
                                }
                                String incodes = EasyExcelUtils.getIncodes(detailId, US_CODE, supplierId);
                                if (stringSet.contains(incodes)) {
                                    continue;
                                }
                                stringSet.add(incodes);
                                cmsGoodsEntity.setIncodes(incodes);
                                cmsGoodsEntity.setGoodid(incodes);
                                cmsGoodsEntity.setIsSampleApply(0);
                                cmsGoodsEntity.setBatch(row.getString("BATCH"));
                                cmsGoodsEntity.setOriginalPrice(new BigDecimal("0.00"));
                                cmsGoodsEntity.setPurchasePrice(new BigDecimal("0.00"));
                                cmsGoodsEntity.setRepertory(StringUtils.isNotEmpty(row.getString("QUANTITY")) ? row.getInteger("QUANTITY") : 0);
                                String warehouseSub = warehouse.substring(0, 2);
                                cmsGoodsEntity.setRepertoryArea(warehouseSub.equals("云岗") ? "北京" : warehouseSub);
                                cmsGoodsEntity.setPublish(1);

                                cmsGoodsEntity.setDescribe(row.getString("PACK").length() > 1 ? row.getString("PACK") : "");
                                cmsGoodsEntity.setFiles("");
                                cmsGoodsEntity.setPayType(0);
                                List<Map<String, String>> ladderPriceList = selfSupportHelper.getLadderPrice(warehouse, row, x);
                                String count = ladderPriceList.get(0).get("min");
                                if (!"0".equals(count)) {
                                    moq = Integer.parseInt(count);
                                }
                                cmsGoodsEntity.setMinimumOrder((long) Math.max(moq, 1));

                                if (warehouse.contains("香港")) {
                                    cmsGoodsEntity.setDeliveryArea(DeliveryAreaEnum.OTHER.getCode());
                                    cmsGoodsEntity.setHongkongDate("1-3个工作日");
                                } else {
                                    cmsGoodsEntity.setHongkongDate("");
                                    cmsGoodsEntity.setDeliveryArea(DeliveryAreaEnum.DOMESTIC.getCode());
                                }
                                if (!arrCollect.contains(detailId)) {
                                    cmsGoodsEntity.setDomesticDate("1-3个工作日");
                                } else {
                                    cmsGoodsEntity.setDomesticDate("3-5个工作日");
                                }
                                cmsGoodsEntity.setIncremental(1L);
                                cmsGoodsEntity.setSource(SourceEnum.DATA_PACKAGE.getCode());
                                cmsGoodsEntity.setMpq(1L);
                                cmsGoodsEntity.setHisp(null);
                                cmsGoodsEntity.setSales(0);
                                cmsGoodsEntity.setClick(0);
                                cmsGoodsEntity.setVisitor(0);
                                cmsGoodsEntity.setCreatedAt(DateUtils.now());
                                cmsGoodsEntity.setUpdatedAt(DateUtils.now());
                                cmsGoodsEntity.setActivityId(0);
                                cmsGoodsEntity.setContent(null);
                                //费率
                                JSONObject data = RateCalculateUtil.getRate(cmsGoodsEntity.getBrandName(), cmsGoodsEntity.getModel());
                                // 费率信息
                                JSONObject rateJsonObject = (JSONObject) data.get(RateCalculateConstants.RATE);
                                cmsGoodsEntity.setRates(rateJsonObject);
                                //关税
                                BigDecimal tariffRate = rateJsonObject.getBigDecimal(RateCalculateConstants.TARIFFRATE_FIELD);
                                //商检税
                                BigDecimal cIQprice = rateJsonObject.getBigDecimal(RateCalculateConstants.CIQPRICE_FIELD);
                                //税费计算和存储
                                if (tariffRate != null) {
                                    cmsGoodsEntity.setTariffsRate(tariffRate.doubleValue());
                                }
                                if (cIQprice != null) {
                                    cmsGoodsEntity.setInspectionChargesFee(cIQprice.doubleValue());
                                }
                                cmsGoodsEntity.setEmbargo(data.get(RateCalculateConstants.EMBARGO_FIELD) == null ? 0 : data.getInteger(RateCalculateConstants.EMBARGO_FIELD));
                                cmsGoodsEntity.setCcc(data.get(RateCalculateConstants.CCC_FIELD) == null ? 0 : data.getInteger(RateCalculateConstants.CCC_FIELD));
                                cmsGoodsEntity.setEccnNo(data.getString(RateCalculateConstants.ECCN_FIELD));

                                Map<String, String> paramMap = new HashMap<>();
                                if ("SUNLORD".equals(brand)) {
                                    paramMap = sunloadMap.get(cmsGoodsEntity.getModel());
                                }
                                // 参数
                                cmsGoodsEntity.setParams(JSONObject.toJSONString(paramMap));
                                // 阶梯价格
                                cmsGoodsEntity.setPrices(JSONObject.toJSONString(ladderPriceList));
//                                if (CollectionUtils.isEmpty(ladderPriceList)) {
//                                    String price = ladderPriceList.get(0).get("price");
//                                    cmsGoodsEntity.setUnitPrice(Double.parseDouble(MathUtil.divide(price, cmsGoodsEntity.getMinimumOrder(), 4)));
//                                } else {
                                cmsGoodsEntity.setUnitPrice(0.0000);
//                                }
                                pojo.setCmsGoodsEntity(cmsGoodsEntity);

                                CmsGoodsInformationEntity cmsGoodsInformationEntity = new CmsGoodsInformationEntity();
                                cmsGoodsInformationEntity.setEcnn(1);
                                cmsGoodsInformationEntity.setAtlas("");
                                cmsGoodsInformationEntity.setContent(null);
                                cmsGoodsInformationEntity.setActivity(0);
                                cmsGoodsInformationEntity.setEcnnnumber("");
                                cmsGoodsInformationEntity.setTariffs(0);
                                cmsGoodsInformationEntity.setGoodid(incodes);
                                cmsGoodsInformationEntity.setTariffsrate(0);
                                cmsGoodsInformationEntity.setInspectionCharges(0);
                                cmsGoodsInformationEntity.setInspectionChargesFee(cmsGoodsEntity.getInspectionChargesFee());
                                cmsGoodsInformationEntity.setParams(null);
                                cmsGoodsInformationEntity.setCreatedAt(new Date());
                                pojo.setCmsGoodsInformationEntity(cmsGoodsInformationEntity);

                                // price
                                List<CmsPricesEntity> pricesEntities = new ArrayList<>(6);
                                for (Map<String, String> m : ladderPriceList) {
                                    CmsPricesEntity pricesEntity = new CmsPricesEntity();
                                    pricesEntity.setLadderid(0);
                                    pricesEntity.setGoodid(incodes);
                                    pricesEntity.setMin(Long.parseLong(m.get("min")));
                                    pricesEntity.setMax(Long.parseLong(m.get("max")));
                                    pricesEntity.setPrice(BigDecimal.valueOf(Double.parseDouble(m.get("price"))));
                                    pricesEntity.setCurrency(Integer.parseInt(m.get("currency")));
                                    pricesEntity.setPosition(Integer.parseInt(m.get("position")));
                                    pricesEntity.setDiscountRate(new BigDecimal(m.get("discount_rate")));
                                    pricesEntity.setDiscountPrice(new BigDecimal(m.get("discount_price")));
                                    pricesEntity.setPublish(0);
                                    pricesEntity.setCreatedAt(new Date());
                                    pricesEntity.setUpdatedAt(new Date());
                                    pricesEntities.add(pricesEntity);
                                }
                                pojo.setCmsPricesEntityList(pricesEntities);
                                objectMaster.add(pojo);

                            }
                        } catch (TargetServerException e) {
                            log.warn("获取自营数据异常");
                            throw new TargetServerException(e.getMessage(), supplierId, SubjectSupplierEnum.SELFSUPPORT.getSubject());
                        } catch (Exception e1) {
                            log.warn("解析自营数据异常，将丢弃此条数据");
                            retryOperateLogHelper.add(rowLineJsonStr, supplierId, e1.toString(), false);
                        }
                    } else {
                        break;
                    }
                }
                page = 1;
            }
        } finally {
            if (objectMaster != null) {
                objectMaster.isCompleted();
                cmsTopicUpdateSumLogService.insertBySum(sum.longValue(), pk);
            }

        }

    }
}
